package com.chuiyuan;

import com.chuiyuan.entity.Rule;
import com.chuiyuan.exception.RuleException;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;

/**
 * Created by chuiyuan on 2/11/16.
 */
public class HttpService {
    /**
     *
     * @param rule
     * @return doc
     */
    public  Document extrace(Rule rule){
        validateRule(rule);

        String url = rule.getUrl();
        String [] params = rule.getParams() ;
        String [] values = rule.getValues() ;
        String resultTagName = rule.getResultTagName() ;
        int type = rule.getType();
        int requestMethod = rule.getRequestMethod() ;
        Document doc =null ;
        try {
            Connection conn = Jsoup.connect(url);
            conn.userAgent("Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.5.0");
            if (params!= null){
                for (int i =0; i<params.length ;i++){
                    conn.data(params[i], values[i]);
                }
            }
            //Document doc = null ;
            switch (requestMethod){
                case  Rule.GET:
                    doc =conn.timeout(10000).get();
                    break;
                case Rule.POST:
                    doc =conn.timeout(10000).post();
                break;
            }
        }catch (IOException e ){
            System.out.println("No network");
            //e.printStackTrace();
        }
        return doc ;
    }

    /**
     * validate input params
     */
    private static void validateRule(Rule rule){
        String url = rule.getUrl() ;
        if (url == null || url.length()==0){
            throw new RuleException("url can't be null");
        }
        if (!url.startsWith("http://")){
            throw  new RuleException("url not in correct format");
        }
        /**
         * not consider total right
         */
        if (rule.getParams()!= null && rule.getValues()!= null){
            if (rule.getParams().length!= rule.getValues().length){
                throw new RuleException("params length!= values length");
            }
        }
    }
}
